﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Beway.ValueAdded.Model.WeiXinModel;

using Beway.ValueAdded.Model;
using Beway.ValueAdded.Service;
 
using System.Configuration;
using System.Globalization;

namespace Beway.ValueAdded.RechargeGateway.Controllers
{
    /// <summary>
    /// 微信红包发送接口
    /// </summary>
    public class WeiXinController: BaseController
    {       

        RechargeServ rs = new RechargeServ();
        ReUserServ rus = new ReUserServ();
        WeiXinRedpackSvc wxSvc = new WeiXinRedpackSvc();

        public ActionResult md5(string str)
        {
            
            string dt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo);
            return Content(beway.common.Encryption.Md5Encry32bit(str));
        }

        /// <summary>
        /// 瀚微红包发放接口（使用瀚微互动微信公众号发放）
        /// </summary>
        /// <param name="userId">瀚微充值平台账户Id</param>
        /// <param name="openId">客户微信openId（瀚微公众号）</param>
        /// <param name="amount">红包金额（100-20000），单元为分</param>
        /// <param name="orderNo">微信红包充值订单号（不需要带微信商户号）</param>
        /// <param name="sendName">红包发送者/商户不超过10个汉字，含标点符号, utf8编码，发送前url编码</param>
        /// <param name="wishing">祝福语不超过20个汉字，含标点符号</param>
        /// <param name="actName">活动名称不超过32个字符，含标点符号</param>
        /// <param name="sign">签名数据</param>
        /// <returns></returns>
        public ActionResult RedpackSend(int userId,string openId,int amount,string orderNo,string sendName,string wishing,string actName,string sign)
        {
            int ret = -10;
            ReUser user = rus.GetByUserId(userId);
            bool isvalidate = UserValidate(Request, Convert.ToDecimal(amount)/100, user, out ret);//客户身份验证
            if (isvalidate)
            {
                string verifyStr = string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}", userId, openId, amount, orderNo, sendName, wishing, actName, user.VerifyMac);
                verifyStr = beway.common.Encryption.Md5Encry32bit(verifyStr);
                if (verifyStr == sign.ToLower()) //验证通过
                {                   
                    Recharge rm = new Recharge()
                    {
                        UserID = userId,
                        OrderAmount = amount,
                        UserOrderNo = orderNo,//调用系统提供的订单号
                        OrderID = orderNo, //红包发放订单号
                        OrderTime = System.DateTime.Now,
                        PayStatus = 0,
                        RCTarget = openId,
                        RCType = 5, //微信红包
                        RechargeErrorReason = "",
                        RechargeStatus = 0,
                        RechargeAmount = amount
                    };
                    int rcid = rs.AddForUniqueOrderNo(rm);
                    if (rcid > 0)
                    {
                        //先更新项目的额度（有可能与实际的总额度有出入，为考虑性能，未做并发控制）
                        user.RechStock -= (Convert.ToDecimal(amount) / 100);
                        rus.UpdateStock(user);

                        //调用充值接口
                        string rpOrderNo = "";//红包订单号
                        string sendErr = "";//发送错误信息
                        if (this.SendWxRedpack(openId, amount, sendName, wishing, actName, orderNo, out rpOrderNo, out sendErr))
                        {
                            ret = 1;//红包发放成功
                            rm.RechargeStatus = 1;
                            rm.RechargeSuccessTime = System.DateTime.Now;
                            rm.OrderID = rpOrderNo;//订单号
                            //成功或处理中也记录错误原因
                            rm.RechargeErrorReason = sendErr;
                        }
                        else
                        {
                            rm.RechargeSuccessTime = System.DateTime.Now;
                            rm.OrderID = rpOrderNo;//订单号
                            rm.RechargeErrorReason = sendErr;
                            ret = 3;//发放失败
                        }

                        //更新充值结果
                        rs.Update(rm);
                    }
                    else
                    {
                        ret = 0;//订单号已存在，请更换
                    }
                }
                else
                {
                    ret = -2;//mac检验失败
                }
            }            

            return Content(ret.ToString());
        }        

        /// <summary>
        /// 发送微信红包
        /// </summary>
        /// <param name="openId">微信openId</param>
        /// <param name="amount">红包金额，单位分</param>
        /// <param name="sendName">红包发送者/商户不超过10个汉字，含标点符号</param>
        /// <param name="wishing">祝福语不超过20个汉字，含标点符号</param>
        /// <param name="actName">活动名称不超过10个汉字，含标点符号</param>
        ///<param name="orderNo">活动平台提供的订单号(28个长度，0-9，a-z A-Z)</param>
        /// <param name="rpOrderNo">微信红包发放订单号</param>   
        /// <param name="err">发送失败错误信息</param>
        private bool SendWxRedpack(string openId, int amount,string sendName,string wishing,string actName,string orderNo,out string rpOrderNo,out string err)
        {
            bool isSend = false;

            PayWeiXin payForWeiXin = new PayWeiXin();
            payForWeiXin.nonce_str = beway.common.StringUtil.GenerateCheckCode(32);

            #region 商户信息从config文件中读取
            //商户支付密钥key
            payForWeiXin.key = ConfigurationManager.AppSettings["key"].ToString();
            //商户号
            payForWeiXin.mch_id = ConfigurationManager.AppSettings["mch_id"].ToString();

            //接收人openId
            payForWeiXin.re_openid = openId;

            //商户 appid 
            payForWeiXin.wxappid = ConfigurationManager.AppSettings["wxappid"].ToString();

            //红包发送者名称 
            payForWeiXin.send_name = sendName;
            //发放金额分
            payForWeiXin.total_amount = amount;
            //红包发放总人数
            payForWeiXin.total_num = 1;
            //红包祝福语
            payForWeiXin.wishing = wishing;
            //活劢名称 
            payForWeiXin.act_name = actName;
            //备注信息 
            payForWeiXin.remark = "remark";

            //调用接口的机器 Ip 地址
            payForWeiXin.client_ip = ConfigurationManager.AppSettings["client_ip"].ToString();
            #endregion

            //号订单信息
            payForWeiXin.mch_billno = payForWeiXin.mch_billno + orderNo;
            rpOrderNo = payForWeiXin.mch_billno;

            payForWeiXin.CertPath = ConfigurationManager.AppSettings["certPath"].ToString();
            payForWeiXin.CertPwd = ConfigurationManager.AppSettings["password"].ToString();
            //string err = "";

            //小于1元，大于200元的，使用携带场景id
            if (payForWeiXin.total_amount<100 || payForWeiXin.total_amount > 20000) 
            {
                payForWeiXin.scene_id = "PRODUCT_3";//PRODUCT_3:虚拟物品兑奖 
            }
            else
            {
                payForWeiXin.scene_id = "PRODUCT_2";//PRODUCT_2:抽奖 
            }

            isSend = wxSvc.SendWeiXinRedpack(payForWeiXin, out err);

            if (!isSend)
            {
                log.Error(err);
            }
            return isSend;
        }
    }
}